#include "UDPSocket.h"

UDPSocket::UDPSocket( )
{


    udpSocket = new QUdpSocket();



    // QObject::connect(udpSocket, &QUdpSocket::readyRead ,[&]()
    // {
    //     QByteArray bytes;
    //     while ( udpSocket->hasPendingDatagrams() )
    //     {
    //         QByteArray datagram;

    //         datagram.resize( udpSocket->pendingDatagramSize() );

    //         udpSocket->readDatagram( datagram.data(), datagram.size() );

    //         bytes.append( datagram );
    //     }
    //     qDebug()<<bytes.toHex();
    // });


}

void UDPSocket::setServerAddress(const std::string &add, int port)
{

    serverAddress = add;
    serverPort    = port;
    // connect(udpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));
}

std::string UDPSocket::getServerAddress()
{
    return serverAddress;
}

int UDPSocket::getServerPort()
{
    return serverPort;
}

void UDPSocket::setLocalPort(int local_port)
{
    localPort = local_port;
    udpSocket->bind( QHostAddress("192.168.1.216"), localPort );
}

int UDPSocket::getLocalPort()
{
    return localPort;
}

int UDPSocket::sendData(const QByteArray &data)
{
    return udpSocket->writeDatagram( data, QHostAddress(serverAddress.data()), serverPort );
}

QByteArray UDPSocket::readData()
{
    QByteArray bytes;

    while ( udpSocket->hasPendingDatagrams() )
    {
        QByteArray datagram;

        datagram.resize( udpSocket->pendingDatagramSize() );

        udpSocket->readDatagram( datagram.data(), datagram.size() );

        bytes.append( datagram );
    }

    return bytes;
}
